﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autofac;
using FizzBuzz.Service;

namespace FizzBuzz.App
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {

                if ((args.Length != 2) && (args.Length != 0))
                {
                    throw new ArgumentException("Invalid number of parameters, either use the default of 1 to 100, or set a lower and upper bound");
                }
                int low = 1;
                int high = 100;

                if (args.Length > 0)
                {
                    if (!int.TryParse(args[0], out low))
                    {
                        throw new ArgumentException("Invalid lower bound");
                    }
                    if (!int.TryParse(args[1], out high))
                    {
                        throw new ArgumentException("Invalid upper bound");
                    }
                }

                var container = Boot();
                var engine = container.Resolve<IFizzBuzz>();

                engine.Run(low, high);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        static IContainer Boot()
        {
            Autofac.ContainerBuilder builder = new Autofac.ContainerBuilder();
            
            builder.RegisterType<FizzBuzz.ServiceImpl.FizzBuzz>()
                .AsImplementedInterfaces()
                .PropertiesAutowired();
            builder.RegisterType<FizzBuzz.ServiceImpl.FizzBuzzRuleEngine>()
                .AsImplementedInterfaces()
                .PropertiesAutowired();
            builder.RegisterType<FizzBuzz.ServiceImpl.TraceOutput>()
                .AsImplementedInterfaces()
                .PropertiesAutowired();
            builder.RegisterType<FizzBuzz.ServiceImpl.Rules.FizzRule>()
                .WithMetadata<IRuleMetadata>(m=>
                    m.For(rm=>rm.RuleOrder, 0)
                    )
                .AsImplementedInterfaces()
                .PropertiesAutowired();
            builder.RegisterType<FizzBuzz.ServiceImpl.Rules.BuzzRule>()
                .WithMetadata<IRuleMetadata>(m =>
                    m.For(rm => rm.RuleOrder, 1)
                    )
                .AsImplementedInterfaces()
                .PropertiesAutowired();
            builder.RegisterType<FizzBuzz.ServiceImpl.Validation.FizzBuzzInputValidator>()
                .AsImplementedInterfaces()
                .PropertiesAutowired();


            return builder.Build();
        }
    }
}
